package com.mocha.nezha.nezha;

import cn.hutool.core.collection.CollectionUtil;
import com.mocha.nezha.dmo.entity.CameraPGEntity;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TODO 杆子 和 杆子 关系 最好是 从算法组 获取；  这样 才会更准确
 *
 * @author songkui
 * @since 2024/3/19 16:00
 */
public class NezhaDeviceManager {

    //key parkCode;
    private final ConcurrentHashMap<String, ParkPoleGraph> parkCameraMapping = new ConcurrentHashMap<>();

    private NezhaDeviceManager() {
    }

    private static final class ManagerHolder {
        static final NezhaDeviceManager manager = new NezhaDeviceManager();
    }

    public static NezhaDeviceManager getInstance() {
        return ManagerHolder.manager;
    }


    /**
     * 1，查询数据库数据转换生成； 2， 如果数据有变动，那么需要同步更新数据【最好是晚上更新数据】
     *
     * @param parkDeviceBuilder :;
     */

    public void initialize(ParkDeviceBuilder parkDeviceBuilder) throws Exception {

        if (CollectionUtil.isEmpty(parkDeviceBuilder.getPoleMap()) || CollectionUtil.isEmpty(parkDeviceBuilder.getPoleEdgeMap())) {
            throw new Exception("Park pole or path is null");
        }
        for (Map.Entry<String, List<PoleVertex>> entry : parkDeviceBuilder.getPoleMap().entrySet()) {
            buildParkPoleGraph(entry.getKey(), entry.getValue(), parkDeviceBuilder.getPoleEdgeMap().get(entry.getKey()), parkDeviceBuilder.getCameraMap().get(entry.getKey()));
        }

    }

    public void buildParkPoleGraph(String parkCode, List<PoleVertex> poleList, List<PoleEdge> poleEdgeList, Map<String, CameraPGEntity> cmap) throws Exception {
        ParkPoleGraph parkCameraGraph = new ParkPoleGraph();
        parkCameraGraph.initializePoleGraph(parkCode, poleList, poleEdgeList, cmap);
        parkCameraMapping.put(parkCode, parkCameraGraph);
    }

    public PoleVertex  getPoleVertexByPoleCode(String parkCode, String poleCode){
        ParkPoleGraph graph = parkCameraMapping.get(parkCode);
        if (null == graph){
            return  null;
        }
        return graph.getPoleVertexByPoleCode(poleCode);
    }

    public List<PoleVertex> findVertexPaths(String parkCode, PoleVertex start, PoleVertex end){
        ParkPoleGraph graph = parkCameraMapping.get(parkCode);
        if (null == graph){
            return  null;
        }
        return graph.findVertexPaths(start, end);
    }

    public  List<PoleEdge> findEdgePaths(String parkCode, PoleVertex start, PoleVertex end){
        ParkPoleGraph graph = parkCameraMapping.get(parkCode);
        if (null == graph){
            return  null;
        }
        return graph.findEdgePaths(start, end);
    }

    public PoleVertex getPoleVertexByCameraCode(String parkCode, String cno){
        ParkPoleGraph graph = parkCameraMapping.get(parkCode);
        if (null == graph){
            return null;
        }

        return graph.getPoleVertexByCameraCode(cno);
    }

}
